package com.jxwifi.cloud.quickcleanserver.mycenter;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.basicactivity.BasicActivity;
import com.bumptech.glide.Glide;
import com.idroid.utils.MToast;
import com.idroid.widget.CircleImageView;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickcleanserver.MainActivity;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.CleaningApplication;
import com.jxwifi.cloud.quickcleanserver.app.Host;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.InfoBean;
import com.jxwifi.cloud.quickcleanserver.bean.UploadBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.upgrade.UpgradeNotice;
import com.jxwifi.cloud.quickcleanserver.utils.Constants;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;

import com.photo.PhotoPickerActivity;
import com.upload.BusinessModule;
import com.upload.ImgUpload;
import com.upload.UpLoadListener;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PackageUtils;

/**
 * 个人资料
 * Created by Administrator on 2019/5/13.
 */

public class PersonalDataActivity extends CleanBasicActivity {
    /**
     * 单选
     */
    public final static int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public final static int MODE_MULTI = 1;
    private static final int PICK_PHOTO = 1;
    @Bind(R.id.et_my_personal_data_name)
    TextView mEtMyPersonalDataName;//生日
    @Bind(R.id.et_my_personal_data_gender)
    TextView mEtMyPersonalDataGender;//性别
    @Bind(R.id.et_my_personal_data_contacts)
    TextView mEtMyPersonalDataContacts;//联系人
    @Bind(R.id.et_my_personal_data_phone)
    TextView mEtMyPersonalDataPhone;//联系电话
    @Bind(R.id.img_personal_data_photo)
    CircleImageView mImgPersonalDataPhone;
    @Bind(R.id.et_my_personal_versioncode)
    TextView mEtMyPersonalVersion;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        ButterKnife.bind(this);
        openEventBus();
    }

    public void initView(){
        if (!TextUtils.isEmpty(AccountMgr.getheadpic(mBaseContext))){
            Glide.with(mBaseContext).load(AccountMgr.getheadpic(mBaseContext)).dontAnimate().into(mImgPersonalDataPhone);
        }else{
            Glide.with(mBaseContext).load(R.mipmap.icon_default_head).dontAnimate().into(mImgPersonalDataPhone);
        }
        if (!TextUtils.isEmpty(AccountMgr.getBirthday(mBaseContext))){
            mEtMyPersonalDataName.setText(AccountMgr.getBirthday(mBaseContext));
        }else{
            mEtMyPersonalDataName.setText("请选择您的生日");
        }
        if (!TextUtils.isEmpty(AccountMgr.getcontactTell(mBaseContext))){
            mEtMyPersonalDataPhone.setText(AccountMgr.getcontactTell(mBaseContext));
        }else{
            mEtMyPersonalDataPhone.setText("请输入联系人电话");
        }
        if (!TextUtils.isEmpty(AccountMgr.getcontactName(mBaseContext))){
            mEtMyPersonalDataContacts.setText(AccountMgr.getcontactName(mBaseContext));
        }else{
            mEtMyPersonalDataContacts.setText("请输入联系人");
        }

        if (!TextUtils.isEmpty(AccountMgr.getsex(mBaseContext))){
            if ("M".equals(AccountMgr.getsex(mBaseContext))){
                mEtMyPersonalDataGender.setText("男");
            }else if ("W".equals(AccountMgr.getsex(mBaseContext))){
                mEtMyPersonalDataGender.setText("女");
            }
        }else{
            mEtMyPersonalDataGender.setText("性别选择");
        }

        if (StateUtils.HOST_ON_LINE.equals(Host.HOST)){
            mEtMyPersonalVersion.setText("当前版本：V" + PackageUtils.getLocalVersionName(mBaseContext));
        }else{
            mEtMyPersonalVersion.setText("当前版本：V" + PackageUtils.getLocalVersionName(mBaseContext)+"(测试环境)");
        }

    }

    @OnClick({R.id.rel_img_back_pressed,R.id.img_personal_data_photo,R.id.tv_sign_out_button,R.id.rel_my_personal_data_name
    ,R.id.rel_my_personal_data_gender,R.id.rel_my_personal_data_contacts,R.id.rel_my_personal_data_phone,R.id.et_my_personal_data_phone,R.id.rel_my_personal_versioncode})
    void clickCK(View v){
        Intent intent = new Intent();
        switch (v.getId()){
            //返回
            case R.id.rel_img_back_pressed:
                onBackPressed();
            break;
            //头像
            case R.id.img_personal_data_photo:
                initphone();
                break;
            //退出登录
            case R.id.tv_sign_out_button:
                outLogin();//退出接口请求，不做操作，现在后台没有返回的操作，只做统计。
                AccountMgr.logout(mBaseContext);
                CleaningApplication.JUMP_TYPE=0;
                intent.setClass(mBaseContext, MainActivity.class);
                intent.putExtra("mainindex", "0");
                startActivity(intent);
                break;
            //生日
            case R.id.rel_my_personal_data_name:
                intent.setClass(mBaseContext,BirthdayActivity.class);
                startActivity(intent);
                break;
            //性别
            case R.id.rel_my_personal_data_gender:
                intent.setClass(mBaseContext,CleaningSexActivity.class);
                startActivity(intent);
                break;
            //紧急联系人
            case R.id.rel_my_personal_data_contacts:
                intent.setClass(mBaseContext,ContactNameActivity.class);
                startActivity(intent);
                break;
            //紧急联系人电话
            case R.id.et_my_personal_data_phone:
            case R.id.rel_my_personal_data_phone:
                intent.setClass(mBaseContext,ContactTellActivity.class);
                startActivity(intent);
                break;
            //检查更新
            case R.id.rel_my_personal_versioncode:
                UpgradeNotice.UpgradeData(mBaseContext, TAG, 0,this);
                break;
        }
    }

    /**
     * 图片选择回调的方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                uploadImg(result.get(0));
            }
        }
    }

    public void outLogin(){
        AuzHttp.get(UrlPool.GET_LOGOUT, new Params(), new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {

            }

            @Override
            public void onFailure(int errorCode, String msg) {

            }
        },TAG);
    }

    //图片上传
    public void uploadImg(String img){
        new ImgUpload(mBaseContext, UrlPool.STORAGE_UPLOAD, img, new UpLoadListener() {
            @Override
            public void onComplete(boolean isSuccess, String response) {

                if (isSuccess) {
                    UploadBean muploadbean = JSON.parseObject(response, UploadBean.class);
                    profile(muploadbean.getUrl());

                } else {
                    Toaster.show(getApplicationContext(), "上传失败，请重试");
                }

            }
        }, TAG).setBusinessModule(BusinessModule.Head).doUpload();
    }

    //修改保洁员信息接口操作 1:birthday 2:emergencyContactName 3:emergencyContactTell 4:headImg 5:sex
    public void profile(String procontent){
        final String cuncontent=procontent;
        Params params=new Params();
        params.add("headImg",procontent);
        AuzHttp.post(UrlPool.POST_UPDATE_PROFILE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code==0){
                    InfoBean mInfoBean= JSON.parseObject(data, InfoBean.class);
                    AccountMgr.putUser(mBaseContext,mInfoBean,false);
                        Glide.with(mBaseContext).load(mInfoBean.getHeadImg()).into(mImgPersonalDataPhone);
                }else{
                    PasswordLogin.passwordlogin(mBaseContext,TAG,AccountMgr.gettell(mBaseContext),AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin){
                        profile(cuncontent);
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        },TAG);
    }

    public void initphone(){
        if (isPermissionGranted(Manifest.permission.CAMERA,
                Constants.QUEST_CODE_CAMERA)) {
            Intent intent=new Intent();
            intent.setClass(mBaseContext, PhotoPickerActivity.class);
            intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);//是否显示相机
            intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, MODE_SINGLE);//单选还是多选
            intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);//最多可选择数量
            startActivityForResult(intent, PICK_PHOTO);
        } else {
            if (Build.VERSION.SDK_INT <= 22) {
                final KAlertDialog dialog = new KAlertDialog(mBaseContext, "相机权限已关闭\", \"相机权限已被禁止，请在设置中开启");
                dialog.setRightTxt("去查看", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //前往应用详情界面
                        try {
                            Uri packUri = Uri.parse("package:" + mBaseContext.getPackageName());
                            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packUri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } catch (Exception e) {
                            MToast.shortToast(mBaseContext, "跳转失败");
                        }
                        dialog.dismiss();
                    }
                });
                dialog.setLeftTxt("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    protected boolean isPermissionGranted(String permissionName, int questCode) {
        //6.0以下系统，取消请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        //判断是否需要请求允许权限，否则请求用户授权
        int hasPermision = mBaseContext.checkSelfPermission(permissionName);
        if (hasPermision != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permissionName}, questCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length == 0) {
            return;
        }
        switch (requestCode) {
            case Constants.QUEST_CODE_CAMERA:
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }
}